<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page.sync="page"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               :search.sync="search"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @refresh-change="refreshChange"
               @on-load="onLoad">
      <template slot="menuLeft">
        <el-button type="danger"
                   size="small"
                   icon="el-icon-delete"
                   plain
                   @click="handleDelete">删 除
        </el-button>
        <el-button
          type="primary"
          size="small"
          plain icon="el-icon-upload2"
          v-if="userInfo.role_name.includes('medical')"
          @click="handleImport">批量导入
        </el-button>
        <el-button type="warning" size="small" plain icon="el-icon-download" @click="handleExport">导出
        </el-button>
      </template>
    </avue-crud>
    <el-dialog title="数据导入" append-to-body :visible.sync="excelBox" width="555px" class="crud-container">
      <avue-form :option="excelOption" v-model="excelForm" :upload-after="uploadAfter">
        <template slot="excelTemplate">
          <el-button type="primary" @click="handleTemplate" plain>
            点击下载模板<i class="el-icon-download el-icon--right"></i>
          </el-button>
        </template>
        <template #isCovered>
          <el-alert
            title="注意，重复向相同批次中导入相同器械将覆盖之前的数据"
            type="warning"
            :closable="false"
            show-icon>
          </el-alert>
        </template>
      </avue-form>
      <avue-crud :data="dataExcel" :option="endOption" v-if="show" style="margin-top: -50px"/>
    </el-dialog>
  </basic-container>
</template>

<script>
  import {getList, getDetail, add, update, remove} from "@/api/business/remainEquipment";
  import option from "@/const/business/remainEquipment";
  import {mapGetters} from "vuex";
  import {getBatchList} from "@/api/business/batchOrderItem";
  import {exportBlob} from "@/api/common";
  import {getToken} from "@/util/auth";
  import func from "@/util/func";
  import NProgress from "nprogress";
  import {downloadXls} from "@/util/util";
  import {dateNow} from "@/util/date";

  export default {
    data() {
      return {
        excelForm: {
          itemList: []
        },
        show:false,
        dataExcel: [],
        search: {},
        templateName: '器械结余留用数据填报模板.xlsx',
        excelBox : false,
        form: {},
        query: {},
        loading: true,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        option: option,
        data: [],
        excelOption: {
          align: "left",
          submitBtn: false,
          emptyBtn: false,
          cancelBtn: true,
          dialogCloseBtn: true,
          column: [
            {
              label: '文件上传',
              prop: 'excelFile',
              type: 'upload',
              drag: true,
              showFileList: false,
              loadText: '文件上传中，请稍等',
              span: 24,
              propsHttp: {
                res: 'data'
              },
              tip: '请上传 .xls,.xlsx 标准格式文件',
              action: "/api/remainEquipment/import-order"
            },
            {
              label: "",
              prop: "isCovered",
              type: "switch",
              align: "center",
              width: 80,
              span: 24,
              value: 0,
              slot: true,
            },
            {
              label: '模板下载',
              prop: 'excelTemplate',
              formslot: true,
              span: 24,
            },
          ]
        },
        endOption: {
          height: "300px",
          showButton: false, // 默认显示按钮
          addBtn: false,
          menu: false,
          refreshBtn: false,
          columnBtn: false,
          column: [
            {
              label: "上传失败器械名称",
              prop: "equipmentName",
              width:200,
              overHidden: true,
            },
            {
              label: "上传失败器械编号",
              prop: "equipmentNo",
              width:200,
            },
          ],
        },
      };
    },
    created() {
      console.log("role_name",this.userInfo.role_name);
      getBatchList().then(res => {
        this.findObject(this.option.column, "batchId").dicData = res.data.data;
      });
    },
    computed: {
      ...mapGetters(["userInfo","permission","loginUserInfo"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.remainEquipment_add, true),
          viewBtn: this.vaildData(this.permission.remainEquipment_view, true),
          delBtn: this.vaildData(this.permission.remainEquipment_delete, true),
          editBtn: this.vaildData(this.permission.remainEquipment_edit, true)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    methods: {
      handleImport() {
        this.show = false;
        this.dataExcel = null;
        this.excelBox = true;
      },
      uploadAfter(res, done, loading, column) {
        console.log(res)
        this.dataExcel = res;
        if (res.length > 0) {
          this.show = true;
        }
        this.refreshChange();
        done();
      },
      handleExport() {
        const batchId = func.toStr(this.search.batchId);
        const year = func.toStr(this.search.year);
        const equipmentName = func.toStr(this.search.equipmentName);

        //console.log("batchId",batchId,"district",district,"year",year,"equipmentName",equipmentName,"instName",instName)
        this.$confirm("是否导出器械结余留用数据?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          NProgress.start();
          exportBlob(`/api/remainEquipment/exportMedicine?${this.website.tokenHeader}=${getToken()}&batchId=${batchId}&year=${year}&equipmentName=${equipmentName}`).then(res => {
            downloadXls(res.data, `器械结余留用统计数据${dateNow()}.xlsx`);
            NProgress.done();
          })
        });
      },
      handleTemplate() {
        exportBlob(`/api/remainEquipment/export-template?${this.website.tokenHeader}=${getToken()}&templateName=${this.templateName}`).then((response) => {
          if(response.data.size > 0){
            let url = window.URL.createObjectURL(response.data);
            let a = document.createElement("a");
            document.body.appendChild(a);
            a.href = url;
            a.download = this.templateName;
            a.click();
            window.URL.revokeObjectURL(url);
          }else{
            this.$message.warning('模板文件不存在!');
          }
        });
      },
      rowSave(row, done, loading) {
        add(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },
      rowUpdate(row, index, done, loading) {
        update(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          console.log(error);
        });
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      beforeOpen(done, type) {
        if (["edit", "view"].includes(type)) {
          getDetail(this.form.id).then(res => {
            this.form = res.data.data;
          });
        }
        done();
      },
      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1;
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
      },
      refreshChange() {
        this.onLoad(this.page, this.query);
      },
      onLoad(page, params = {}) {
        this.loading = true;
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      }
    }
  };
</script>

<style>
.crud-container {
  height: 1000px; /* 设置弹窗的高度 */
}
</style>
